// app.js
const openIdUrl = require('config').openIdUrl
App({
  data: {
    windows_width: 200,
    windows_height: 200,
  },
  //require决定路径配置
  require: function ($uri) { return require($uri) },

  onLaunch() {
    var that = this;
    // 展示本地存储能力
    const logs = wx.getStorageSync('logs') || []
    logs.unshift(Date.now())
    wx.setStorageSync('logs', logs)
    console.log("begin main app");
    this.getUserOpenId();

    var _width = 100;
    var _height = 100;
    wx.getSystemInfo({
      success: function (res) {
        _width = res.windowWidth; // 新的显示区域宽度
        _height = res.windowHeight; // 新的显示区域高度
      }
    });
    that.data.windows_width = _width;
    that.data.windows_height = _height;

    // 登录
    // this.getUserOpenId(function(err, openid) {
    // if (!err) {
    //  to do some code.......  
    // } else {
    //   console.log('err:', err)
    //   self.setData({
    //     loading: false
    //   })
    // }
    // });
  },
  onShow(options) {
    // Do something when show.
  },
  onHide() {
    // Do something when hide.
  },
  onError(msg) {
    console.log(msg)
  },
  //全局变量配置，getApp().globalData.userInfo访问
  globalData: {
    openid: null,
    userInfo: {},
    demovar: "hello world",   
  },
  // 发送 res.code 到后台换取 openId, sessionKey, unionId
  getUserOpenId: function (callback) {
    var self = this

    if (self.globalData.openid) {
      callback(null, self.globalData.openid)
    } else {
      wx.login({
        success: function (data) {
          console.log(data);
          // wx.request({
          //   url: openIdUrl,
          //   data: {
          //     code: data.code
          //   },
          //   success: function (res) {
          //     console.log('拉取openid成功', res)
          //     self.globalData.openid = res.data.openid
          //     callback(null, self.globalData.openid)
          //   },
          //   fail: function (res) {
          //     console.log('拉取用户openid失败，将无法正常使用开放接口等服务', res)
          //     callback(res)
          //   }
          // })
        },
        fail: function (err) {
          console.log('wx.login 接口调用失败，将无法正常使用开放接口等服务', err)
          callback(err)
        }
      })
    }
  }
})
